package com.xbe.redis;

import com.xbe.common.utils.DateUtils;
import com.xbe.equipment.domain.Equipment;
import com.xbe.equipment.service.IEquipmentService;
import com.xbe.netty.NettyServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @Author: liuzhiting
 * @Desctription: TODO
 * @Date: Created in 2020-08-12 16:24
 * @Version: 1.0
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener
{
    private static final Logger log = LoggerFactory.getLogger("on-off-line");
    @Autowired
    private IEquipmentService equipmentService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer)
    {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern)
    {
        String sim = message.toString();
        Equipment equipment = equipmentService.selectEquipmentBySim(sim);
        if (equipment != null)
        {
            RedisKeyExpirationListener.log.info("sim【{}】{}秒没收到数据,最后更新时间为【{}】,状态改为【离线】", sim,
                                                NettyServerHandler.expiredSim,
                                                DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",
                                                                         equipment.getUpdateTime()));

            //修改设备状态

            equipment.setState("1");
            equipmentService.updateEquipmentBySim1(equipment);

            //剔除map中该键值对
            NettyServerHandler.map.remove(sim);


            //剔除Ipmap中该键值对
            NettyServerHandler.ipMap.remove(sim);
        }


    }
}


